import csv
import math
import random
import os

from rich import print
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
from rich.table import Table

from .emptyDataRemove import emptyDataRemove
from .cutData import cutData
from .deduplication import deduplication
from .search import searchContent
from .tensor import tensor
from .save import save

# import sys
# sys.path.insert(0, sys.path[0]+"../")

# from .fileList import file 
console = Console()


class fileEntity:

    fileUrl = ''

    totalPage = 0
    nowPage = 1

    fileData = []
    fileDataSearch = []

    def __clear(self):
        os.system('cls')
        os.system('clear')

    def __init__(self,fileEntityUrl):

        self.fileData = []
        self.fileDataSearch = []

        self.__clear()

        self.fileUrl=fileEntityUrl
        self.__showFileInformation()

        print(fileEntityUrl)

        pass

    def __showFileInformation(self):
        index = 0
        with open(f'{self.fileUrl}', encoding='utf-8-sig') as f:
            for row in csv.reader(f, skipinitialspace=True):                
                self.fileData.append(row)
                index+=1
        self.totalPage = math.ceil(index/20)
        f.close()

        self.__fileView()

    def __switchPage(self,page):
        self.nowPage = page
        self.__fileView()

    def __fileView(self,status=1,message='',isSearch=False):
        self.__clear()
        print(self.fileUrl)
        data = None
        if isSearch == False: data = self.fileData
        else: data = self.fileDataSearch

        table = Table(title=f"文件视图 页数{self.nowPage}/{self.totalPage}",header_style="bold magenta",expand=True,caption_justify="center")
  
        for column in data[0:1][0]:
             table.add_column(column)
        for line in data[self.nowPage*20-20:self.nowPage*20]:
            table.add_row(*line)

        # print(self.fileData[1:2][0][1])

        console.print(table)

        if status == -1: console.print("错误的命令！\n",style="bold red")
        if status == -2: console.print("错误的页数！\n",style="bold red")
        if status == 3: console.print(f"{message}",style="bold green")

        self.__showFunctionListTips()

        
    
    def __showFunctionListTips(self):
        console.print("【S 值】筛选 【CUT start end】数据切割  【fill 匹配关键词 替换值】替换 【dedup 指定列】数据去重 【miao】显示形状 【tensor 列明】张量转换 【back】返回文件列表 【random】打乱 【save】保存文件")
        console.print("$命令：",end="")
        instruct = input()
        if instruct == 'A' or instruct == 'a':
            pass
        elif instruct == 'random' or instruct == 'RANDOM':
            randomArray = random.sample(self.fileData[1:], len(self.fileData[1:]))
            self.fileData = self.fileData[:1]+randomArray
            self.__fileView(3,'成功打乱')
        elif 'fill' in instruct or 'FILL' in instruct:
            information = instruct.split(' ')
            index = 1
            for i in self.fileData:
                indexChild = 0
                for o in i:
                    if information[1] in o:
                        self.fileData[index-1][indexChild] = information[2]
                    indexChild+=1
                index+=1
            self.__fileView(3,'成功替换')
        elif 'tensor' in instruct or 'TENSOR' in instruct:
            information = instruct.split(' ')
            tensorEntity = tensor(self.fileData,information[1])
            arrayMiao = tensorEntity.getTensorArray()
            self.fileData = arrayMiao
            self.__fileView()
        elif instruct == 'save' or instruct == 'save':
            save(self.fileData)
            self.__fileView(3,'成功保存数据')
        elif 's' in instruct or 'S' in instruct:
            information = instruct.split(' ')
            a = searchContent()
            miao =  a.searchContentMiao(self.fileData,information[1])
            if miao == -1:
                self.__fileView(3,'未搜索到内容',False)
            else:
                self.fileDataSearch = miao
                self.__fileView(3,'【Q 退出搜索视图】',True)
        elif instruct == 'q' or instruct == 'Q':
            self.fileDataSearch = []
            self.__fileView()

        elif instruct == 'clear' or instruct == 'CLEAR':
            emptyDataRemove(self.fileData)
            self.__fileView(3,'成功清除空数据')


        elif instruct == 'back' or instruct == 'BACK':
            from ..fileList import file 
            fileMiao = file()
            fileMiao.getFileList()
        
        elif 'CUT' in instruct or 'cut' in instruct:

            cutArray = instruct.split(" ")
            cutData(self.fileData,cutArray[1],cutArray[2])
            self.__fileView(3,"成功切割数据，已输出到【output】文件夹")

        elif 'dedup' in instruct or 'DEDUP' in instruct:
            information = instruct.split(' ')
            a = deduplication()
            self.fileData = a.dedup(self.fileData,information[1])
            self.__fileView(3,"成功去除重复数据")

        elif  'page' in instruct or 'PAGE' in instruct:
            try:
                instructArray = instruct.split(' ')
                if int(instructArray[1]) > self.totalPage:
                    self.__fileView(-2)
                self.__switchPage(int(instructArray[1]))
            except ValueError:
                self.__fileView(-1)
        elif   instruct == 'miao' or   instruct == 'MIAO':
            width = 0
            for i in self.fileData[0]:
                width+=1
            self.__fileView(3,f'{width},{len(self.fileData)}')
        else:
            self.__fileView(-1)
    
    def saveFile():
        pass